<?php
/**
 * @copyright Copyright (c) 2015 wstech LLC
 * @author 57620133@qq.com
 *
 * \common\wosotech\Util::generateOid();
 *
 */

namespace common\wosotech;

class Util 
{
    public static function W($obj="", $log_file='')
    {
        if (is_array($obj))
            $str = print_r($obj, true);
        else if(is_object($obj))         
            $str = print_r($obj, true);                        
        else 
            $str = "{$obj}";

        if (empty($log_file))
            $log_file = \Yii::$app->getRuntimePath().'/errors.log';
            
        $date =date("Y-m-d H:i:s");
        $log_str = sprintf("%s,%s\n",$date,$str);
        error_log($log_str, 3, $log_file);
    }

    public static function C($url, $get = [], $post = [], $format = 'json') 
    {
        $requestUrl = $url . "?";
        foreach ($get as $k => $v) {
            $requestUrl .= "$k=" . urlencode($v) . "&";
        }
        $requestUrl = substr($requestUrl, 0, -1);
        return Util::curl($requestUrl, $post);        		
    }

    public static function curl($url, $posts = [], $format = 'json') {
    	$response = self::curl_core($url, $posts);
    	if ('json' === $format) {
    		return json_decode($response, true);  
    	} else if ('xml' === $format) {
    		$respObject = @simplexml_load_string($response);
    		if (false !== $respObject)
    			return json_decode(json_encode($respObject), true); 
    		else
    			throw new \Exception ('XML error:'.$response);
    	}
    }

    public static function generateOid()
    {
    	return strtoupper(uniqid());
    }

    public static function curl_core($url, $posts = []) {
    	$curlOptions = [
    		CURLOPT_USERAGENT => 'WXTPP Client',
    		CURLOPT_CONNECTTIMEOUT => 30,
    		CURLOPT_TIMEOUT => 30,
    		CURLOPT_SSL_VERIFYPEER => false,
    		CURLOPT_POST => true,
    		CURLOPT_POSTFIELDS => is_string($posts) ? $posts : json_encode($posts),
    		CURLOPT_RETURNTRANSFER => true,
    		CURLOPT_URL => $url,
    		CURLOPT_SSL_VERIFYPEER => false,
    		CURLOPT_SSL_VERIFYHOST => false,
    		CURLOPT_SSLVERSION => CURL_SSLVERSION_TLSv1,            
    	];

    	$curlResource = curl_init();
    	foreach ($curlOptions as $option => $value) {
    		curl_setopt($curlResource, $option, $value);
    	}
    	$response = curl_exec($curlResource);
    	
    	$responseHeaders = curl_getinfo($curlResource);

    	// check cURL error
    	$errorNumber = curl_errno($curlResource);
    	$errorMessage = curl_error($curlResource);

    	curl_close($curlResource);

    	if ($errorNumber > 0) {
    		throw new \Exception('Curl error requesting "' .  $url . '": #' . $errorNumber . ' - ' . $errorMessage);
    	}
    	if (strncmp($responseHeaders['http_code'], '20', 2) !== 0) {
    		throw new \Exception('Request failed with code: ' . $responseHeaders['http_code'] . ', message: ' . $response);
    	}

    	//self::W($response);
    	return $response;
    }

    // U::getWxUserHeadimgurl("http://wx.qlogo.cn/mmopen/17ASicSl2de5EHEpImf7IOxZ5w6MibiaWuzsThDo39s0Lq6U0ZG4Kn04AJDfK4XiaxYicCCpsXH3UxW8goFcPnEkfhv7GO2AeFAtR/0", 64);
    public static function getWxUserHeadimgurl($url, $size)
    {
        if (empty($url))
            return $url;
        if (!in_array($size, [0, 46, 64, 96, 132]))
            return $url;
        $pos = strrpos($url, "/");
        $str = substr($url, 0, $pos) . "/$size";
        return $str;
    }

    public static function mobileIsValid($mobile)
    {    
        $pattern = '/^1\d{10}$/';
        if(preg_match($pattern, $mobile))        
            return true;            
        return false;
    }

    public static function getYesNoOptionName($key = null)
    {
        $arr = array(
            '0' => '否',
            '1' => '是',
        );        
        return $key === null ? $arr : (isset($arr[$key]) ? $arr[$key] : '');
    }

    const RANDOM_DIGITS = 'digits';
    const RANDOM_NONCESTRING = 'noncestr';

    public static function randomString($type = self::RANDOM_DIGITS, $len = 4) {
        $code = '';
        switch ($type) {
            case self::RANDOM_DIGITS:
                $chars = '0123456789';
                break;
            case self::RANDOM_NONCESTRING:
                $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
                break;
        }
        $chars_len = strlen($chars);
        while ($len > 0) {
            $code .= substr($chars, rand(0, 10000) % $chars_len, 1);
            $len--;
        }
        return $code;
    }

    public static function timeago( $ptime ) {
        $ptime = strtotime($ptime);
        $etime = time() - $ptime;
        if($etime < 1) return '刚刚';
        $interval = array (
            12 * 30 * 24 * 60 * 60  =>  '年前' . ' (' . date('Y-m-d', $ptime) . ')',
            30 * 24 * 60 * 60       =>  '个月前' . ' (' . date('m-d', $ptime) . ')',
            7 * 24 * 60 * 60        =>  '周前' . ' (' . date('m-d', $ptime) .')',
            24 * 60 * 60            =>  '天前',
            60 * 60                 =>  '小时前',
            60                      =>  '分钟前',
            1                       =>  '秒前'
        );
        foreach ($interval as $secs => $str) {
            $d = $etime / $secs;
            if ($d >= 1) {
                $r = round($d);
                return $r . $str;
            }
        };
    }

    static public function getSessionOpenid() {
        if (YII_ENV_DEV) {
            $model = \common\models\MktUser::findOne(4);
            return $model->openid;
        }
        if (!empty(\Yii::$app->request->get('openid'))) {
            return \Yii::$app->request->get('openid');
        } else if (!empty(\Yii::$app->session->get('openid'))) {
            return \Yii::$app->session->get('openid');
        } else {
             $wxapp =  \common\models\WxGh::getDefaultGh()->loadWx()->getApplication();
             $oauth = $wxapp->oauth;
             if (empty(\Yii::$app->request->get('code'))) {
                 $oauth->redirect()->send();
                 exit;                                  
             }

             $user = $oauth->user();
             $token = $user->getToken()->toArray();        
             $openid = $token['openid'];        
             /*        
             [
                 'access_token' => 'xxx',
                 'expires_in' => 7200,
                 'refresh_token' => 'yyy',
                 'openid' => 'oD8xWwg-GJiFi9RLEllEzR1bwJ9A',
                 'scope' => 'snsapi_userinfo',
             ]
             */
             
             if ('snsapi_userinfo' == $token['scope'])
             {
                 $originalUser = $user->getOriginal();
                 //yii::error($originalUser);
                 /*        
                 [
                     'openid' => 'oD8xWwg-GJiFi9RLEllEzR1bwJ9A',
                     'nickname' => 'xx',
                     'sex' => 1,
                     'language' => 'zh_CN',
                     'city' => 'x',
                     'province' => 'xx',
                     'country' => 'xx',
                     'headimgurl' => 'http://wx.qlogo.cn/mmopen/Uf2Tkt1hetGliaFhJPGqIk23ZyE0Y7AFCmefYQAbic2yNRdjO0ZsepFlWA2CHUcewXsqdGIQ0q5nvCIxVJmkAUFzORhqraI5Mp/0',
                     'privilege' => [],
                 ]
                 */      
             }
                     
             \Yii::$app->session['openid'] = $openid;
             \Yii::info("new a openid=$openid");                     
             return $openid;
         }            
    }

    static public function getSessionUserId()
    {
        if (!empty(\Yii::$app->request->get('myUserId'))) {
            return \Yii::$app->request->get('myUserId');
        } else if (!empty(\Yii::$app->session->get('myUserId'))) {
            return \Yii::$app->session->get('myUserId');
        } else {
            $model = \common\models\MktUser::findOne(['openid' => self::getSessionOpenid()]);
            \Yii::$app->session['myUserId'] = $model->id;
            return $model->id;
        }
    }

    public static function haveProbability($probability=10)
    {
        return mt_rand(0,1000000) < $probability;
    }

    public static function getShortString($str, $len, $suffix='...') 
    {
        $s = mb_substr($str, 0, $len, 'UTF-8');
        if ($s == $str) {
            return $str;
        }
        return $s . '...';
    }

    public static function getShortInt($num) 
    {
        if ($num >= 10000)
            return sprintf("%2.0f", $num / 10000) . 'W';    
        else if ($num >= 1000)    
            return sprintf("%2.1f", $num / 1000) . 'K';    
        else
            return "$num";
    }

}

